package com.example.redis.demo;

import org.json.JSONObject;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClientConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.params.SetParams;

import java.util.List;

/**
 * @author chenxuanwen
 * @Date: 2023/11/1  21:33
 */
public class JedisDemo {
    private static int COMMAND_NUM = 1000;

    private static String REDIS_HOST = "127.0.0.1";

    public static void main(String[] args) {
        DefaultJedisClientConfig build = DefaultJedisClientConfig.builder().password("123456").build();
        Jedis jedis = new Jedis(REDIS_HOST, 6379,build);
        withoutPipeline(jedis);
        withPipeline(jedis);
        getWithPipeline(jedis);
    }

    private static void withoutPipeline(Jedis jedis) {
        Long start = System.currentTimeMillis();
        for (int i = 0; i < COMMAND_NUM; i++) {
            jedis.set("no_pipe_" + String.valueOf(i), String.valueOf(i), SetParams.setParams().ex(60));
        }
        long end = System.currentTimeMillis();
        long cost = end - start;
        System.out.println("withoutPipeline cost : " + cost + " ms");
    }

    private static void withPipeline(Jedis jedis) {
        Pipeline pipe = jedis.pipelined();
        long start_pipe = System.currentTimeMillis();
        for (int i = 0; i < COMMAND_NUM; i++) {
            pipe.set("pipe_" + String.valueOf(i), String.valueOf(i), SetParams.setParams().ex(60));
        }
        pipe.sync(); // 获取所有的response
        long end_pipe = System.currentTimeMillis();
        long cost_pipe = end_pipe - start_pipe;
        System.out.println("withPipeline cost : " + cost_pipe + " ms");
    }
    private static void getWithPipeline(Jedis jedis) {
        Pipeline pipe = jedis.pipelined();
        long start_pipe = System.currentTimeMillis();
        for (int i = 0; i < COMMAND_NUM; i++) {
            //pipe.set("pipe_" + String.valueOf(i), String.valueOf(i), SetParams.setParams().ex(60));
            pipe.get("pipe_" + String.valueOf(i));
        }
        List<Object> objects = pipe.syncAndReturnAll();// 获取所有的response
        System.out.println(JSONObject.valueToString(objects));
        long end_pipe = System.currentTimeMillis();
        long cost_pipe = end_pipe - start_pipe;
        System.out.println("getWithPipeline cost : " + cost_pipe + " ms");
    }
}
